﻿//-----------------------------------------------------------------------
// <copyright file="TeamFoundationServer.cs" company="CodePlex">
//     Copyright (c) Doug Holland, CodePlex. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CodePlex.Diagnostics
{
    using System;

    using CodePlex.Diagnostics.Contracts;

    /// <summary>
    /// Represents an instance of Microsoft Team Foundation Server where exceptions and log entries are promoted to work items.
    /// </summary>
    public sealed class TeamFoundationServer
    {
        #region public TeamFoundationServer(Uri uri)
        
        /// <summary>
        /// Initializes a new instance of the <see cref="T:TeamFoundationServer"/> class.
        /// </summary>
        /// <param name="uri">The <see cref="T:System.Uri"/> representing the Microsoft Team Foundation Server.</param>
        public TeamFoundationServer(Uri uri)
        {
            this.Uri = uri;
        } 

        #endregion

        #region public Uri Uri

        /// <summary>
        /// Gets the <see cref="T:System.Uri"/> representing the Microsoft Team Foundation Server.
        /// </summary>
        /// <value>The <see cref="T:System.Uri"/> representing the Microsoft Team Foundation Server.</value>
        public Uri Uri
        {
            get;
            private set;
        }

        #endregion

        #region public void Register()

        /// <summary>
        /// Registers the instance of Microsoft Team Foundation Server with the CodePlex.Diagnostics database.
        /// </summary>
        public void Register()
        {
            // initialize a new data contract based upon the Uri of the Team Foundation Server.
            TeamFoundationServerDataContract contract = new TeamFoundationServerDataContract(this.Uri);

            DiagnosticsServiceClient client = null;

            try
            {
                // establish a proxy to the diagnostics service.
                client = new DiagnosticsServiceClient();

                // register the Team Foundation Server instance.
                IAsyncResult result = client.BeginRegisterTeamFoundationServer(contract, null, null);

                // complete the registration of the Team Foundation Server instance.
                client.EndRegisterTeamFoundationServer(result);

                // causes the client to transition from its current state into the closed state.
                client.Close();
            }
            catch
            {
                // causes the client to transition immediately from its current state into the closed state.
                if (client != null)
                {
                    client.Abort();
                }
            }
        }

        #endregion
    }
}
